import {session, stoage} from './util'

const NotLoginAuth = [
    '/',
    '/login',
    '/admin',
    '/register',
    '/register/complete',
    '/register/fail',
    '/forgetpassword'
]
/**
 * 分角色控制权限和菜单
 */
const RoleAssentPath = {
    GUEST : [
        ...NotLoginAuth,
    ],
    USER : [
        ...NotLoginAuth,
        '/',
        '/publish',
        '/publish/add',
        '/publish/list',
    ],
    COMPANY : [
        ...NotLoginAuth,
        '/',
        '/company',
        '/company/supplement',
        '/user',
        '/user/list',
        '/user/add',
        '/user/edit/*',
        '/publish',
        '/publish/list',
    ],
    ADMIN : [
        ...NotLoginAuth,
        '/',
        '/channel',
        '/channel/add',
        '/channel/list',
        '/channel/edit/*',
        '/company',
        '/company/add',
        '/company/list',
        '/company/edit/*',
    ],
}

export const getRoute = () => { return RoleAssentPath[getUser().role] }

let LoginInfo = {
    account : {},
    logined : false,
    username : null,
    role : 'GUEST', // ADMIN | COMPANY | USER | GUEST
}

export const Login = (userInfo, remember) =>{
    LoginInfo = {
        ...userInfo,
        account : userInfo.account,
        logined : true,
        lastime : new Date().getTime(),
    }
    if(remember){
        stoage.setStore('UserInfo', LoginInfo)
    }
    session.setStore('UserInfo', LoginInfo)
}

export const Update = (account) =>{
    let storeUser = stoage.getStore('UserInfo')
    let sessionUser = session.getStore('UserInfo')
    if(storeUser && storeUser.logined){
        storeUser.account = account;
        stoage.setStore('UserInfo', storeUser)
    }
    sessionUser.account = account;
    session.setStore('UserInfo', sessionUser)
    LoginInfo.account = account
}

export const LoginOut = () =>{
    LoginInfo = {
        logined : false,
        role : 'GUEST',
    }
    session.removeStore('UserInfo')
    stoage.removeStore('UserInfo')
}

export const getUser = () =>{
    if(LoginInfo.logined === false){
        let storeUser = stoage.getStore('UserInfo')
        if(storeUser && storeUser.logined){ Login(storeUser) }
    }
    return LoginInfo
}

export const matchList = (regexs, str) =>{
    if(regexs.indexOf(str.toLocaleLowerCase()) != -1){ return true }
    let matched = regexs.find(regex => {
        if(regex.indexOf('*') == -1){ return false }
        let matchs = regex.substring(0, regex.indexOf('*'))
        return str.toLocaleLowerCase().startsWith(matchs)
    })
    return matched
}

export default (nextState, replace) => {
    let path = nextState.location.pathname.toLocaleLowerCase()
    if(path == '/loginout'){
        LoginOut()
        replace('/login')
    }else if(!matchList(NotLoginAuth, path) && getUser().logined == false){
        replace('/login')
    }else if(!matchList(getRoute(), path)){
        console.log('没有权限:' + path)
        replace('/error/401')
    }
}